package org.gongzhen.HomeController;
import lombok.extern.slf4j.Slf4j;
import org.gongzhen.Category;
import org.gongzhen.HomeService.PostService;
import org.gongzhen.Post;
import org.gongzhen.Result;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;


@RestController
@RequestMapping("/posts")
public class PostController {

    private static final Logger log = LoggerFactory.getLogger(PostController.class);


    @Autowired
    private PostService postService;

    /**
     * 首页
     * @return
     */
    @GetMapping("/getAllPost")
    public Result getPost() {
        List<Post> allPost = postService.getAllPost();
        return Result.success(allPost);
    }

    /**
     * 帖子列表查询
     */
    @GetMapping
    public Result list(){
        List<Post> postList = postService.getAllPost();
        log.info("帖子列表查询");

        return Result.success(postList);
    }

    /**
     * 根据id删除帖子
     */
    @DeleteMapping
    public Result deletePost(Integer id){
        log.info("根据id删除帖子 id = {}",id);
        postService.deleteById(id);

        return Result.success();
    }

    /**
     * 添加帖子
     */
    @PostMapping
    public Result addPost(@RequestBody Post post){
        log.info("添加帖子 ={}",post);
        postService.addPost(post);

        return Result.success();
    }

    /**
     * 根据id查询帖子
     */
    @GetMapping("/{id}")
    public Result getById(@PathVariable Integer id){
        log.info("根据id查询帖子 id={}",id);
        Post post = postService.getById(id);

        return Result.success(post);
    }

    /**
     * 修改帖子（仅帖子发布者可调用）
     */
    @PutMapping("/{id}")
    public Result updatePost(@PathVariable Integer id,@RequestBody Post post){
        log.info("修改帖子 id={},用户={}",id,post);
        postService.updateById(id,post);

        return Result.success();
    }

    /**
     * 根据分类id查询帖子
     */
    @GetMapping("/list/{categoryId}")
    public Result getByCategoryId(@PathVariable Integer categoryId){
        log.info("根据分类id查询帖子 id = {}",categoryId);
        List<Post> categoryList = postService.getByCategoryId(categoryId);

        return Result.success(categoryList);
    }

    /**
     * 点赞帖子
     */
    @PutMapping("/{id}/like")
    public Result likePost(@PathVariable Integer id){
        log.info("点赞帖子 id = {}",id);
        postService.like(id);

        return Result.success();
    }

    /**
     * 收藏帖子
     */
    @PutMapping("/{id}/save")
    public Result collectPost(@PathVariable Integer id){
        log.info("收藏帖子 id = {}",id);
        postService.collectPost(id);

        return Result.success();
    }


}
